package com.shen.util;

import com.shen.pojo.ConsumInfo;
import com.shen.pojo.MobileCard;
import com.shen.pojo.Scene;
import com.shen.server.NetPackage;
import com.shen.server.ServicePackage;
import com.shen.server.SuperPackage;
import com.shen.server.TalkPackage;
import com.shen.server.serive.CallService;
import com.shen.server.serive.SendService;
import sun.nio.ch.Net;

import java.io.*;
import java.util.*;

/**
 * Author:shen
 * CreateDate:2020/6/11.
 * Function:
 */
public class CardUtil {
    static Map<String, MobileCard> cardMap=new HashMap<>();//搜搜移动用户列表
    static Map<String, List<ConsumInfo>> consumInfos=new HashMap<>();//所有卡号的消费记录
    static RandomUtil random=new RandomUtil();

    static {
        cardMap.put("13965756432",new MobileCard("13965756432","小明","123",new NetPackage(),68,100,0,0,0));
       List<ConsumInfo> consumInfoList=new ArrayList<>();
       consumInfoList.add(new ConsumInfo("13965756432","通话",5));
        consumInfos.put("13965756432",consumInfoList);
    }
    /**
     * 根据id查询
     */
    public MobileCard selectMobileCard(String card){
        return cardMap.get(card);
    }
    /**
     * 更新map数据
     */
    public void updateCardMap(MobileCard mobileCard){
        cardMap.put(mobileCard.getCardNumber(),mobileCard);
    }
    /**
     * 查询该卡号是否注册
     */
    public MobileCard isExistCard(String number,String password){
        MobileCard mobileCard=null;
        for (Map.Entry<String,MobileCard> entry:cardMap.entrySet()) {
            if(entry.getKey().equals(number)&&entry.getValue().getPassWord().equals(password)){
                mobileCard=entry.getValue();
            }
        }
        return mobileCard;
    }
    /**
     * 生成新卡
     */
    public String createNumber(){
        return "139"+random.randomNumber(100000000, 10000000);
    }
    /**
     * 注册新卡
     */
    public MobileCard addCard(MobileCard mobileCard){
        cardMap.put(mobileCard.getCardNumber(), mobileCard);
        return cardMap.get(mobileCard.getCardNumber());
    }
    /**
     * 本月账单查询
     */
    public void showAmountDetail(String card){
        MobileCard mobileCard = cardMap.get(card);
        StringBuffer sb=new StringBuffer();
        sb.append("您的卡号:"+mobileCard.getCardNumber()+",当月的账单:\n");
        sb.append("套餐资费："+mobileCard.getServicePackage().price+"元\n");
        sb.append("合计："+mobileCard.getConsumAmount()+"元\n");
        sb.append("账户余额："+mobileCard.getMoney()+"元");
        System.out.println(sb);
    }

    /**
     * 套餐余量查询
     */
    public void showRemainDetail(String card){
        //获取用户卡
        MobileCard mobileCard = cardMap.get(card);
        int remainTalkTime;//剩余通话时间
        int remainSmsCount;//剩余短信条数
        int remainFlow;//剩余流量
        //获得用户的套餐
        StringBuffer sb=new StringBuffer();
        sb.append("您的卡号："+mobileCard.getCardNumber()+",套餐内剩余：\n");
        //判断套餐类型
        if(mobileCard.getServicePackage() instanceof TalkPackage){
            //话痨套餐
            TalkPackage talkPackage=(TalkPackage)mobileCard.getServicePackage();
            remainTalkTime=mobileCard.getRealTalkTime()<talkPackage.getTalkTime() ? talkPackage.getTalkTime()-mobileCard.getRealTalkTime():0;
            sb.append("通话时长："+remainTalkTime+"分钟\n");
            remainSmsCount=mobileCard.getRealSMSCount()<talkPackage.getSmsCount() ? talkPackage.getSmsCount()-mobileCard.getRealSMSCount():0;
            sb.append("短信条数："+remainSmsCount+"条\n");
        }else if(mobileCard.getServicePackage() instanceof SuperPackage){
            //超人套餐
            SuperPackage superPackage=(SuperPackage) mobileCard.getServicePackage();
            remainTalkTime=mobileCard.getRealTalkTime()<superPackage.getTalkTime() ? superPackage.getTalkTime()-mobileCard.getRealTalkTime():0;
            sb.append("通话时长："+remainTalkTime+"分钟\n");
            remainSmsCount=mobileCard.getRealSMSCount()<superPackage.getSmsCount() ? superPackage.getSmsCount()-mobileCard.getRealSMSCount():0;
            sb.append("短信条数："+remainSmsCount+"条\n");
            remainFlow= mobileCard.getRealFlow()<superPackage.getFlow()? superPackage.getFlow()-mobileCard.getRealFlow():0;
            sb.append("上网流量："+Common.dataFormat(remainFlow*1.0/1024)+"GB\n");
        }else if(mobileCard.getServicePackage() instanceof NetPackage){
            //网虫套餐
            NetPackage netPackage=(NetPackage)mobileCard.getServicePackage();
            remainFlow= mobileCard.getRealFlow()<netPackage.getFlow()? netPackage.getFlow()-mobileCard.getRealFlow():0;
            sb.append("上网流量："+Common.dataFormat(remainFlow*1.0/1024)+"GB\n");
        }
        System.out.println(sb);
    }

    /**
     * 打印消费详单
     */
    public void printConsumInfo(String number){
        List<ConsumInfo> consumInfoList = consumInfos.get(number);
        if(consumInfoList!=null){
            Writer writer=null;
            try {
                writer=new FileWriter(new File("demo35/src/"+number+"消费记录.txt"));
                StringBuffer stringBuffer=new StringBuffer();
                stringBuffer.append("**************"+number+"的消费记录**************\n");
                stringBuffer.append("序号\t类型\t数据\t(通话(分钟)/上网(MB)/短信(条))\n");
                for (int i = 0; i < consumInfoList.size(); i++) {
                    stringBuffer.append((i+1)+consumInfoList.get(i).getType()+"\t\t"+consumInfoList.get(i).getConsumData()+"\t\n");
                }
                System.out.println(stringBuffer.toString());
                writer.write(stringBuffer.toString());
                writer.flush();
                System.out.println("消息记录打印完毕！");
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(writer!=null){
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
         }else{
            System.out.println("对不起，不存在此号码的消费记录，不能打印！");
        }
    }
    /**
     * 办理退网
     */
    public MobileCard delCard(String card){
        return cardMap.remove(card);
    }
    /**
     * 套餐变更
     */
    public void changingPack(MobileCard mobileCard,int packNumber){
        //客户本身的套餐
        ServicePackage servicePackage =mobileCard.getServicePackage();
        if(packNumber==1){
            //话痨套餐
            if(servicePackage instanceof TalkPackage){
                System.out.println("对不起，您已经是该套餐用户，无需更换套餐！");
            }else{
                checkUserCanPayMenu(mobileCard,new TalkPackage());
            }
        }else if(packNumber==2){
            //网虫套餐
            if(servicePackage instanceof NetPackage){
                System.out.println("对不起，您已经是该套餐用户，无需更换套餐！");
            }else{
                checkUserCanPayMenu(mobileCard,new NetPackage());
            }

        }else if(packNumber==3){
            //超人套餐
            if(servicePackage instanceof SuperPackage){
                System.out.println("对不起，您已经是该套餐用户，无需更换套餐！");
            }else{
                checkUserCanPayMenu(mobileCard,new SuperPackage());
            }

        }
    }
    /**
     * 检查余额是否能支付套餐费用,并支付
     */
    public void checkUserCanPayMenu(MobileCard mobileCard,ServicePackage servicePackage){
        if (mobileCard.getMoney()>=servicePackage.price ){
            //余额
            mobileCard.setMoney(mobileCard.getMoney()-servicePackage.price);
            //消费
            mobileCard.setConsumAmount(mobileCard.getConsumAmount()+servicePackage.price);
            //清空实际消费数据
            mobileCard.setRealTalkTime(0);
            mobileCard.setRealFlow(0);
            mobileCard.setRealSMSCount(0);
            //更换套餐
            mobileCard.setServicePackage(servicePackage);
            System.out.println("更换套餐成功！");
            System.out.println(mobileCard.getServicePackage().toString());
        }else{
            System.out.println("对不起，您的余额不足以支付新套餐本月消费，请充值后再办理更换套餐业务！");
        }
    }
    /**
     * 话费充值
     */
    public void chargeMoney(MobileCard mobileCard,double money){
        mobileCard.setMoney(money+mobileCard.getMoney());
    }
    /**
     * 消费场景
     */
    public Scene initScenes(int num){
        List<Scene> list=new ArrayList<Scene>();
        list.add(0,new Scene("通话",90,"问候客户,谁知其如此难缠，通话90分钟"));
        list.add(1,new Scene("通话",30,"询问妈妈身体状况，本地通话30分钟"));
        list.add(2,new Scene("短信",5,"参与环境保护实施方案问卷调查，发送短信5条"));
        list.add(3,new Scene("短信",50,"通知朋友手机换号，发送短信50条"));
        list.add(4,new Scene("上网",1024,"和女友微信视频聊天，使用流量1GB"));
        list.add(5,new Scene("上网",1024*2,"晚上手机在线观看韩剧，不留神睡着了，使用流量2GB"));
        return list.get(num);
    }
    /**
     * 添加消费
     */
    public void addConsumInfo(MobileCard mobileCard,ConsumInfo consumInfo){
        if( consumInfos.containsKey(mobileCard.getCardNumber())){
            List<ConsumInfo> consumInfoList = consumInfos.get(mobileCard.getCardNumber());
            consumInfoList.add(consumInfo);
        }else{
            List<ConsumInfo> list=new ArrayList<ConsumInfo>();
            consumInfos.put(mobileCard.getCardNumber(),list);
            list.add(consumInfo);
        }

    }
    /**
     * 模拟消费
     */
    public void utilSoso(MobileCard mobileCard){
        //用户的套餐
        ServicePackage servicePackage = mobileCard.getServicePackage();
        //各个场景数据
        Random random=new Random();
        int temp=0;
        do{
            //随机生成0-5数字
            int ranNum = random.nextInt(6);
            //获得使用场景
            Scene scene = initScenes(ranNum);
            switch (ranNum){
                case 0:
                case 1:
                    if(servicePackage instanceof CallService){
                        //执行通话的方法
                        System.out.println(scene.getDescription());
                        //类型转换
                        CallService talkPackage=(CallService) servicePackage;
                        //执行
                        try {
                           temp= talkPackage.call(scene.getData(),mobileCard);
                            System.out.println("temp:"+temp);
                        } catch (Exception e) {
                            System.err.print(e.getMessage());
                        }
                        //增加一条消费信息
                        ConsumInfo consumInfo=new ConsumInfo(mobileCard.getCardNumber(),scene.getType(),scene.getData());
                        addConsumInfo(mobileCard,consumInfo);
                        break;
                    }else{
                        continue;
                    }
                case 2:
                case 3:
                    if(servicePackage instanceof SendService){
                        //执行通话的方法
                        System.out.println(scene.getDescription());
                        //类型转换
                        SendService sendService=(SendService) servicePackage;
                        //执行
                        try {
                            temp = sendService.send(scene.getData(), mobileCard);
                            System.out.println("temp:"+temp);
                        } catch (Exception e) {
                            System.err.print(e.getMessage());
                        }
                        //增加一条消费信息
                        ConsumInfo consumInfo=new ConsumInfo(mobileCard.getCardNumber(),scene.getType(),scene.getData());
                        addConsumInfo(mobileCard,consumInfo);
                        break;
                    }else{
                        continue;
                    }
                case 4:
                case 5:
                    if(servicePackage instanceof NetPackage){
                        //执行通话的方法
                        System.out.println(scene.getDescription());
                        //类型转换
                        NetPackage netPackage=(NetPackage) servicePackage;
                        //执行
                        try {
                             temp = netPackage.netPlay(scene.getData(), mobileCard);
                            System.out.println("temp:"+temp);
                        } catch (Exception e) {
                            System.err.print(e.getMessage());
                        }
                        //增加一条消费信息
                        ConsumInfo consumInfo=new ConsumInfo(mobileCard.getCardNumber(),scene.getType(),scene.getData());
                        addConsumInfo(mobileCard,consumInfo);
                        break;
                    }else{
                        continue;
                    }
            }
            break;
        }while (true);

    }
    /**
     * 资费说明
     */
    public void showDescription(MobileCard mobileCard){
        List<ConsumInfo> consumInfoList = consumInfos.get(mobileCard.getCardNumber());
        File file=new File("demo35/src/"+mobileCard.getCardNumber()+"消费记录.txt");
        if(file.exists()){
            Reader reader=null;
            try {
                reader=new FileReader(file);
                char[] bytes=new char[1024];
                int len=0;
                while ((len=reader.read(bytes))!=-1){
                    reader.read(bytes,0,bytes.length);
                }
                System.out.println(new String(bytes,0,bytes.length));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(reader!=null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else{
            System.out.println("该用户没有花费，没有相关记录！");
        }
    }
}
